package com.sysu.minsysu.zxcx;

import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringEscapeUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import android.util.Log;

import com.yao.http.HttpRequester;
import com.yao.http.HttpRespons;

public class NewsNetwork {
	static final String webSite = "http://news2.sysu.edu.cn/";
	static final String BBSSysuSite = "http://bbs.sysu.edu.cn/";
	
	public static ArrayList<LinkNode> getNews(){
		try {
			HttpRequester requester = new HttpRequester();
			HttpRespons hr = requester.sendGet(webSite + "ShowList.aspx?ArticleTypeID=1001");
			
			Parser parser = Parser.createParser(hr.getContent(), "utf-8");

			try{
				NodeList nodeList = parser.extractAllNodesThatMatch( new NodeFilter() {
					
					@Override
					public boolean accept(Node arg0) {
						if( arg0 instanceof TableTag ){
							String id = ((TableTag) arg0).getAttribute("id");
							if( id!=null && id.equals("ctl00_ContentPlaceHolder1_ArticleListGV"))
								return true;
							
						}
						return false;
					}
				});
				
				TableTag tag = (TableTag)nodeList.elementAt(0);
				String rawString = tag.getStringText();
				//System.out.println(rawString);
				
				int now=0;
				int length=rawString.length();
				ArrayList<LinkNode> links = new ArrayList<LinkNode>();
				while( now!=-1){
					now = rawString.indexOf("<a href", now);
					if( now==-1 )
						break;
					LinkNode newNode = new LinkNode();
					now = rawString.indexOf('"', now);
					int t = rawString.indexOf('"',now+1);
					newNode.link = rawString.substring(now+1, t);
					
					now = rawString.indexOf('>', t);
					t = rawString.indexOf('<', now);
					newNode.title = rawString.substring(now+1, t);
					now = t;
					links.add(newNode);
					//System.out.println( newNode.title + " --> " + newNode.link);
				}
				return links;
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getArticleContent( String url ){
		try {
			HttpRequester requester = new HttpRequester();
			HttpRespons hr = requester.sendGet(webSite + url);
			
			Parser parser = Parser.createParser(hr.getContent(), "utf-8");
			
			NodeList nodeList = parser.extractAllNodesThatMatch( new NodeFilter() {
				
				@Override
				public boolean accept(Node arg0) {
					if( arg0 instanceof Span){
						String id= ((Span)arg0).getAttribute("id");
						if( id!=null && id.equals("ctl00_ContentPlaceHolder1_ArticleContent")){
							return true;
						}
					}
					return false;
				}
			});
			
			Span span = (Span)nodeList.elementAt(0);
			NodeList nodes = span.getChildren();
			StringBuffer res = new StringBuffer("");
//			for( int i=0; i<nodes.size(); i++ ){
//				Node n = nodes.elementAt(i);
//				if( n.getText().equals("div")){
//					Div div = (Div)n;
//					//div.
//					String temp = div.getStringText();
//					temp = temp.replaceAll("<br>", "\n");
//					Pattern pattern = Pattern.compile("<.+?>");
//					Matcher matcher = pattern.matcher(temp);
//					temp= matcher.replaceAll("");
//					res.append(StringEscapeUtils.unescapeHtml( temp ));
//					res.append('\n');
//					}
//			}
//			if( res.equals("")){
				String temp = span.getStringText();
				temp = temp.replaceAll("<br>", "\n");
				
				Pattern pattern = Pattern.compile("<img.+?>");
				Matcher matcher = pattern.matcher(temp);
				temp = matcher.replaceAll("(图片)");
				
				pattern = Pattern.compile("<.+?>");
				matcher = pattern.matcher(temp);
				temp= matcher.replaceAll("");
				
				res.append(StringEscapeUtils.unescapeHtml( temp ));
				res.append('\n');
//			}
//			Node node = span.getChild(0);
//			String string = node.toPlainTextString();
//			String s = StringEscapeUtils.unescapeHtml(string);
			return res.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static class LinkNode implements Serializable{
		String title;
		String link;
	}
	
	public static ArrayList<LinkNode> getBBSgoodbrd() {
		// TODO Auto-generated method stub
		try {
			HttpRequester requester = new HttpRequester();
			HttpRespons hr = requester.sendGet(BBSSysuSite);
			
			Parser parser = Parser.createParser(hr.getContent(), "GB2312");
//			Parser parser = Parser.createParser(hr.getContent(),hr   
//                  .getContentEncoding());
			try{
				NodeList nodeList = parser.extractAllNodesThatMatch( new NodeFilter() {
				
					@Override
					public boolean accept(Node arg0) {
						if( arg0 instanceof Div ){
							String id = ((Div) arg0).getAttribute( "id" );
							if( id!=null && id.equals( "goodbrd" )){
//								Log.d("BBS","id find" );
								return true;
							}
						}
//						Log.d("BBS id","id not find" );
						return false;
					}
				});
				
				Div tag = (Div) nodeList.elementAt(0);
				String rawString = tag.getStringText();
				Log.d("BBS element", rawString);
				
				int now=0;
				int length=rawString.length();
				ArrayList<LinkNode> links = new ArrayList<LinkNode>();
				while( now != -1){
					now = rawString.indexOf("<a href", now);//int java.lang.String.indexOf(int c, int start)
					if( now == -1 )
						break;
					LinkNode newNode = new LinkNode();
					
					now = rawString.indexOf('>', now);
					int t = rawString.indexOf('<', now);
					//get title
					String intValue = rawString.substring(now+1, t);
//					String gb2312Value =  new String(intVlue, "GB2312"); 					
//					byte [] iso8859Value;
//					iso8859Value = gb2312Value.getBytes("8859_1"); //涓棿鐢↖SO-8859-1杩囨浮
//					String title = new String(iso8859Value, "utf-8"); //杞崲鎴怗B2312瀛楃		

//		            String title = new String(intValue.getBytes("GB2312"),"utf-8");
		            String title = URLEncoder.encode(intValue, "utf-8");
					newNode.title = title;	
					
					now = rawString.indexOf("<a href", now);
					now = rawString.indexOf('"', now);
					t = rawString.indexOf('"',now+1);
					//get the url from location now+1 to t
					newNode.link = rawString.substring(now+1, t);
					//newNode.link = rawString.substring(now+1, now+4) + t + rawString.substring(now+5, t);
					links.add(newNode);
					now = t;
					Log.d("bbs content", newNode.title + " --> " + newNode.link);
				}
				return links;
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static class BBSLinkNode implements Serializable{
		String title;
		String link;
		String description;
	}
	
}
